import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Upload, Icon, message, Button} from 'antd';
import {FILES_API} from '../constants';
import {injectIntl} from './intl';
const basePath = fetch.basePath || '';

class FileUpload extends PureComponent {
    static getDerivedStateFromProps(props, state) {
        if(state.default && props.fileList.length)
            return {
                fileList: props.fileList.map(item => ({
                    uid: item.fileId,
                    name: item.fileName,
                    status: 'done',
                    response: {
                        payload: [item]
                    },
                    url: `${FILES_API.files}/${item.fileId}`
                })),
                default: false
            };
        return null;
    }
    state = {
        loading: false,
        fileList: [],
        default: true,
    }
    beforeUpload = file => {
        const isLt20M = file.size / 1024 / 1024 < 500;
        if(!isLt20M)
            message.error(this.props.intl.formatMessage({
                id: 'fileUpload.valitate.sizeFailed',
                defaultMessage: '文件需小于500M'
            }));
        const canUpload = file.type === 'image/png' || file.type === 'image/jpeg';
        if(!canUpload)
            message.error(this.props.intl.formatMessage({
                id: 'fileUpload.valitate.canUploadPng',
                defaultMessage: '请上传png或jpg格式的图片'
            }));
        return isLt20M && canUpload;
    }
    handleChange = ({file, fileList}) => {
        if(file.status === 'uploading')
            this.setState({loading: true});

        if(file.status === 'done') {
            const fileInfo = file.response.payload.map(item => ({
                fileId: item.id,
                fileName: item.fileName
            }));
            this.setState({
                loading: false
            });
            this.props.onChange(fileInfo);
            message.success(this.props.intl.formatMessage({
                id: 'fileUpload.valitate.succeed',
                defaultMessage: '上传成功！'
            }));
            fileList = fileList.map(item => {
                if(!item.response) return item;
                return ({
                    ...item,
                    url: `${FILES_API.files}/${item.response.payload[0].id}`
                });
            });
        }
        if(file.status === 'error') {
            this.setState({
                loading: false
            });
            message.error(this.props.intl.formatMessage({
                id: 'fileUpload.valitate.failed',
                defaultMessage: '上传失败！'
            }));
        }
        this.setState({fileList: file.status ? [...fileList] : this.state.fileList});
    }
    onRemove = file => {
        const {payload = []} = file.response || {};
        if(payload[0])
            return this.props.onRemove({fileName: payload[0].fileName,
                fileId: payload[0].id ? payload[0].id : payload[0].fileId});
    }
    render() {
        const {formatMessage} = this.props.intl;
        return (
            <Upload
                name="file"
                fileList={this.state.fileList}
                onRemove={this.onRemove}
                beforeUpload={this.beforeUpload}
                action={`${basePath}${FILES_API.files}`}
                multiple={false}
                onChange={this.handleChange}>
                <Button className="ant-upload-text">
                    <Icon type={this.state.loading ? 'loading' : 'plus'} />{formatMessage({
                        id: 'fileUpload.btn.title',
                        defaultMessage: '上传附件'
                    })}</Button>
            </Upload>
        );
    }
}

FileUpload.propTypes = {
    children: PropTypes.string,
    disabled: PropTypes.bool,
    fileList: PropTypes.array,
    intl: PropTypes.object,
    onChange: PropTypes.func,
    onRemove: PropTypes.func,
};

export default injectIntl(FileUpload);
